//
//  TokenCacheManager.m
//  PigMarket
//
//  Created by Felix on 2019/4/11.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "TokenCacheManager.h"

#define kMemberTokenPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"memberToken"]

@implementation TokenCacheManager

@synthesize memberToken = _memberToken;

+(instancetype)sharedInstance {
    
    static TokenCacheManager *instance;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[TokenCacheManager alloc] init];
    });
    
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        //从沙盒中获取数据
        [self initData];
    }
    return self;
}
- (void)initData {
    _memberToken = [NSKeyedUnarchiver unarchiveObjectWithFile:kMemberTokenPath];
}
static NSString *memberLockObj = @"memberToken";

- (void)setMemberToken:(NSString *)memberToken {
    @synchronized (memberLockObj) {
        
        _memberToken = memberToken;
        if (_memberToken) {
            [NSKeyedArchiver archiveRootObject:_memberToken toFile:kMemberTokenPath];
        } else {
            NSFileManager *defaultManager = [NSFileManager defaultManager];
            if ([defaultManager isDeletableFileAtPath:kMemberTokenPath]) {
                [defaultManager removeItemAtPath:kMemberTokenPath error:nil];
            }
        }
    }
}
- (void)clearMemberToken:(NSString *)memberToken {
    @synchronized (memberLockObj) {
        
        if (![memberToken isEqualToString:_memberToken]) {
            return;
        }
        
        _memberToken = nil;
        [NSKeyedArchiver archiveRootObject:_memberToken toFile:kMemberTokenPath];
    }

}
- (NSString *)memberToken {
    return _memberToken;
}

@end
